package day12;

public class InputOutputDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Resource resource = new Resource();
		new Thread(new Input(resource)).start();
		new Thread(new Output(resource)).start();
		

	}

}
//同一个资源：可以用单例去实现，也可以在输入和输出线程构造函数中传递一个相同的资源对象进取
class Resource {
	public String name;
	public String sex;
	public boolean flag = false;
}
class Input implements Runnable{
	private Resource resource;

	//为了让输入输出操作同一个资源
	public Input(Resource resource) {
		this.resource = resource;
	}
	@Override
	public void run() {
		//方便用于两个不用资源名称的切换，便于看到效果
		int j = 0;
		synchronized(resource) {
			while(true) {
				if (resource.flag) {
					try {
						resource.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(j == 0) {
					resource.name = "雨雨雨雨雨雨雨雨雨";
					resource.sex = "menmenmen";
				} else {
					resource.name = "丽丽丽丽丽丽丽丽丽";
					resource.sex = "女女女女";
				}
				//做切换
				j = (j+1) % 2;
				resource.flag = true;
				resource.notify();
			}
		}
	}
	
	
}
class Output implements Runnable{
	private Resource resource;
	
	public Output(Resource resource) {
		this.resource = resource;
	}

	@Override
	public void run() {
		synchronized(resource) {
			while (true) {
				//System.out.println(resource.name + "..." + resource.sex);
				if (!resource.flag) {
					try {
						resource.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				for (int i = 0; i < resource.name.length(); i++) {
					System.err.print(resource.name.charAt(i)+ "  ");
				}
				System.err.println();
				resource.flag = false;
				resource.notify();
			}
		}
	}
	
	
}